// lib/screens/my/my_page.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

import '../../api/auth_api.dart';
import '../../routes/app_routes.dart';

class MyPage extends StatefulWidget {
  const MyPage({super.key});

  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  String _userName = '未登录';
  String _userAvatarUrl = 'https://via.placeholder.com/150'; // 默认头像 URL
  String? _currentUserId; // <--- ADD THIS: To store the current user's ID

  // ImagePicker 实例
  final ImagePicker _picker = ImagePicker();

  @override
  void initState() {
    super.initState();
    _loadUserInfo();
  }

  Future<void> _loadUserInfo() async {
    final prefs = await SharedPreferences.getInstance();
    final String? storedUsername = prefs.getString('current_username');
    final String? storedAvatarUrl = prefs.getString('current_user_avatar');
    final String? storedUserId = prefs.getString('current_user_id'); // <--- Retrieve User ID

    setState(() {
      _userName = storedUsername ?? '未登录';
      _userAvatarUrl = (storedAvatarUrl != null && storedAvatarUrl.isNotEmpty)
          ? storedAvatarUrl
          : 'https://via.placeholder.com/150';
      _currentUserId = storedUserId; // <--- Set the User ID
    });
  }

  Future<void> _logout() async {
    await AuthApi().logout();
    setState(() {
      _userName = '未登录';
      _userAvatarUrl = 'https://via.placeholder.com/150';
      _currentUserId = null; // <--- CLEAR User ID on logout
    });
    Navigator.of(context).pushNamedAndRemoveUntil(AppRoutes.loginScreen, (route) => false);
    print('用户退出登录');
  }

  /// 选取图片并上传
  Future<void> _pickAndUploadImage() async {
    if (_userName == '未登录') {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请先登录才能修改头像。')),
      );
      return;
    }

    try {
      final XFile? image = await _picker.pickImage(source: ImageSource.gallery);

      if (image != null) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('正在上传头像...')),
        );

        final String newAvatarUrl = await AuthApi().uploadAvatar(image.path);

        setState(() {
          _userAvatarUrl = newAvatarUrl;
        });

        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('头像上传成功！')),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('已取消选择图片。')),
        );
      }
    } catch (e) {
      print('图片上传或选择失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('头像上传失败: ${e.toString()}')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的'),
      ),
      body: Column(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(20.0),
            child: Column(
              children: [
                GestureDetector(
                  onTap: _pickAndUploadImage,
                  child: CircleAvatar(
                    radius: 50,
                    backgroundImage: NetworkImage(_userAvatarUrl),
                    backgroundColor: Colors.blueGrey,
                    onBackgroundImageError: (exception, stackTrace) {
                      print('头像图片加载失败: $exception');
                      setState(() {
                        _userAvatarUrl = 'https://via.placeholder.com/150';
                      });
                    },
                    child: _userAvatarUrl == 'https://via.placeholder.com/150'
                        ? const Icon(Icons.person, size: 60, color: Colors.white)
                        : null,
                  ),
                ),
                const SizedBox(height: 16),
                Text(
                  _userName,
                  style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                ),
              ],
            ),
          ),
          const Divider(),
          // My Posts button
          Card(
            margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
            elevation: 2,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            child: ListTile(
              leading: const Icon(Icons.post_add, color: Colors.green),
              title: const Text('我的发布'),
              trailing: const Icon(Icons.arrow_forward_ios, size: 18),
              // Button is enabled only if user is logged in (i.e., _currentUserId is not null/empty)
              onTap: () {
                Navigator.pushNamed(context, AppRoutes.userPosts);
              },
            ),
          ),
          // My Collections button
          Card(
            margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
            elevation: 2,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            child: ListTile(
              leading: const Icon(Icons.collections_bookmark, color: Colors.deepOrange),
              title: const Text('我的收藏'),
              trailing: const Icon(Icons.arrow_forward_ios, size: 18),
              onTap: () {
                Navigator.pushNamed(context, AppRoutes.collectedPosts);
              },
            ),
          ),
          // Browse History button
          Card(
            margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
            elevation: 2,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            child: ListTile(
              leading: const Icon(Icons.history, color: Colors.blue),
              title: const Text('浏览历史'),
              trailing: const Icon(Icons.arrow_forward_ios, size: 18),
              onTap: () {
                Navigator.pushNamed(context, AppRoutes.history);
              },
            ),
          ),
          // Settings button
          ListTile(
            leading: const Icon(Icons.settings),
            title: const Text('设置'),
            onTap: () {
              print('设置');
            },
          ),
          const Spacer(),
          Padding(
            padding: const EdgeInsets.all(20.0),
            child: ElevatedButton(
              onPressed: _userName == '未登录' ? null : _logout,
              style: ElevatedButton.styleFrom(
                minimumSize: const Size.fromHeight(50),
                backgroundColor: Colors.redAccent,
                foregroundColor: Colors.white,
              ),
              child: const Text('退出登录', style: TextStyle(fontSize: 18)),
            ),
          ),
          const SizedBox(height: 20),
        ],
      ),
    );
  }
}